package cn.edu.njust.epms.controller;

import cn.edu.njust.epms.entity.HRRecord;
import cn.edu.njust.epms.entity.User;
import cn.edu.njust.epms.entity.UserDetails;
import cn.edu.njust.epms.service.HRService;
import cn.edu.njust.epms.common.R;
import cn.edu.njust.epms.common.Resp;
import cn.edu.njust.epms.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 健康上报控制器
 *
 */
@RestController
@RequestMapping("/HealthReport")
public class HRController {
    @Autowired
    HRService hs;

    @Autowired
    UserService us;
    /**
     * 健康上报
     * 前台传入上报用户的身份证号以及体温状态，
     * 系统记录当前时间，完成上报。
     * 返回码为1：上报成功
     * 返回码为0：上报失败，原因见msg
     * @param
     * @return
     */
    @PostMapping
    public Resp<HRRecord> report(@RequestBody HRRecord r,HttpServletRequest request){
        User user = (User)request.getSession().getAttribute("user");
        if(r.getPid()==null){
            return Resp.error("请选择用户！");
        }
        if(r.getuTemp()==null)
            return Resp.error("请选择您的体温状态！");
//        System.out.println(r);
        UserDetails ud = us.selectUdByPid(r.getPid());
        if(ud == null)
            return Resp.error("该身份证号不存在！");
        Integer _uId = ud.getuId();
        if(_uId != user.getuId()){
            return Resp.error("上报失败，该账号不可为"+r.getPid()+"上报");
        }
        return hs.HealthReport(r.getPid(), r.getuTemp());
    }

    /**
     * 健康上报记录展示
     * 前台传入筛选条件，返回带有分页信息的结果。
     * @param request
     * @param r
     * @return
     */
    @PostMapping("/list")
    public Resp<PageInfo<HRRecord>> selectByPage(HttpServletRequest request, @RequestBody R r){

        //从session中获取用户登录信息，对于非管理员，只能查询自己的记录，对于游客，拒绝访问
//        System.out.println(r);
        User user = (User)request.getSession().getAttribute("user");
        if(user == null)//没有登录，拒绝访问
            return Resp.error("查询失败：拒绝访问");
        Integer uId = user.getuId();
        if(user.getuSts() != 2)
            r.setuId(uId);
        Integer _pageNo = 1;//默认分页参数
        Integer _size = 5;
        String order="rId";
        if (r.getPageNo() != null) {
            _pageNo = r.getPageNo();
        }
        if (r.getSize() != null) {
            _size = r.getSize();
        }
        if (r.getOrder()!=null && r.getOrder().length()>0) {//没有传入排序，则默认以aId排序
            order = r.getOrder();
        }
        PageHelper.startPage(_pageNo,_size,order);
        Resp<List<HRRecord>> listResp = hs.selectByCondition(r);
        PageInfo<HRRecord> pageInfo = new PageInfo<>(listResp.getData());
        return Resp.success(pageInfo);
    }

    /**
     * 健康上报记录下载
     * @param request
     * @param response
     */
    @GetMapping("list/download")
    public void export(HttpServletRequest request, HttpServletResponse response){
        HSSFWorkbook book = new HSSFWorkbook();
        String FileName = "HealthReport_"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".xls";
        HSSFSheet sheet1 = book.createSheet("sheet1");
        Resp<List<HRRecord>> arrayListResp = hs.selectByCondition(new R());
//        System.out.println(record1);
        List<HRRecord> data = arrayListResp.getData();
        HSSFRow row0 = sheet1.createRow(0);
        sheet1.setColumnWidth(0,8*256);
        sheet1.setColumnWidth(1,17*256);
        sheet1.setColumnWidth(2,24*256);
        sheet1.setColumnWidth(3,20*256);
        sheet1.setColumnWidth(4,6*256);
        row0.createCell(0).setCellValue("上报ID");
        row0.createCell(1).setCellValue("上报人");
        row0.createCell(2).setCellValue("上报人身份证号");
        row0.createCell(3).setCellValue("上报时间");
        row0.createCell(4).setCellValue("体温>=37.3℃？");
        for (int i = 1; i <= data.size(); i++) {
            HRRecord record = data.get(i - 1);
            HSSFRow row = sheet1.createRow(i);
            row.createCell(0).setCellValue(record.getrId());
            row.createCell(1).setCellValue(record.getUd().getName());
            row.createCell(2).setCellValue(record.getPid());
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            row.createCell(3).setCellValue(format.format(record.getrTime()));
            row.createCell(4).setCellValue(record.getuTemp()?"是":"否");
        }
        response.setHeader("Content-Disposition","attachment; filename="+FileName);
        response.setContentType("application/binary;charset=ISO8859_1");
        response.setCharacterEncoding("GB2312");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            book.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 健康上报记录删除
     * 慎用！！！！
     * @param r
     * @return
     */
    @PostMapping("/list/delete")
    public Resp<String> deleteHRRecord(HRRecord r){
        return hs.deleteHRRecord(r);
    }

    @GetMapping("/list/not_report")
    public void downloadNotReport(HttpServletResponse response){
        HSSFWorkbook book = new HSSFWorkbook();
        String FileName = "notReport_"+new SimpleDateFormat("yyyyMMddHHmm").format(new Date())+".xls";
        HSSFSheet sheet1 = book.createSheet("sheet1");
        List<UserDetails> data = hs.selectUdNotHRToday();
        HSSFRow row0 = sheet1.createRow(0);
        sheet1.setColumnWidth(0,8*256);
        sheet1.setColumnWidth(1,17*256);
        sheet1.setColumnWidth(2,24*256);
        sheet1.setColumnWidth(3,20*256);
        sheet1.setColumnWidth(4,24*256);
        row0.createCell(0).setCellValue("用户id");
        row0.createCell(1).setCellValue("姓名");
        row0.createCell(2).setCellValue("身份证号");
        row0.createCell(3).setCellValue("手机号");
        row0.createCell(4).setCellValue("地址");
        for (int i = 1; i <= data.size(); i++) {
            UserDetails record = data.get(i - 1);
            HSSFRow row = sheet1.createRow(i);
            row.createCell(0).setCellValue(record.getuId());
            row.createCell(1).setCellValue(record.getName());
            row.createCell(2).setCellValue(record.getPid());
            row.createCell(3).setCellValue(record.getPhone());
            row.createCell(4).setCellValue(record.getAddr());
        }
        response.setHeader("Content-Disposition","attachment; filename="+FileName);
        response.setContentType("application/binary;charset=ISO8859_1");
        response.setCharacterEncoding("GB2312");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            book.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
